package com.gzsxy.sso.core.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 自定义认证服务器异常处理 --response异常解析
 * @date 2021/11/8 16:23
 */
@Component("CustomWebResponseExceptionTranslator")
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {



    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
        if (e instanceof InternalAuthenticationServiceException) {
            InternalAuthenticationServiceException interException = (InternalAuthenticationServiceException)e;
            return ResponseEntity.status(HttpStatus.OK)
                    .body(new CustomOAuthException(interException.getMessage()));
        //InvalidGrantException 密码错误异常
        } else if (e instanceof InvalidGrantException){
            return ResponseEntity.status(HttpStatus.OK)
                    .body(new CustomOAuthException("用户名或者密码错误"));
        } else if (e instanceof OAuth2Exception){
            OAuth2Exception oAuth2Exception = (OAuth2Exception)e;
            return ResponseEntity.status(oAuth2Exception.getHttpErrorCode())
                    .body(new CustomOAuthException(oAuth2Exception.getMessage()));
        } else {
            return ResponseEntity.status(HttpStatus.OK)
                    .body(new CustomOAuthException(e.getMessage()));
        }
    }
}
